// https://leetcode.cn/problems/non-overlapping-intervals/description/

// 算法思路总结：
// 1. 贪心策略处理无重叠区间问题
// 2. 按区间左端点排序，便于顺序处理
// 3. 维护当前保留区间的左右边界
// 4. 当发生重叠时，保留结束较早的区间（移除结束较晚的）
// 5. 时间复杂度：O(nlogn)，空间复杂度：O(1)

#include <iostream>
using namespace std;

#include <vector>
#include <algorithm>

class Solution 
{
public:
    const int INF = 0x3f3f3f3f;
    int eraseOverlapIntervals(vector<vector<int>>& intervals) 
    {
        int m = intervals.size();

        sort(intervals.begin(), intervals.end(), [](const vector<int>& v1, const vector<int>& v2){
            return v1[0] < v2[0];
        });

        int ret = 0;
        int l = -INF, r = -INF;
        for (int i = 0 ; i < m ; i++)
        {
            if (r <= intervals[i][0])
                l = intervals[i][0], r = intervals[i][1];
            else
            {
                if (r > intervals[i][1])
                {
                    l = intervals[i][0];
                    r = intervals[i][1];
                }
                ret++;
            }
        }

        return ret;        
    }
};                                            

int main()
{
    vector<vector<int>> vv1 = {{1,2}, {2,3}, {3,4}, {1,3}};
    vector<vector<int>> vv2 = {{1,2}, {1,2}, {1,2}};

    Solution sol;

    cout << sol.eraseOverlapIntervals(vv1) << endl;
    cout << sol.eraseOverlapIntervals(vv2) << endl;

    return 0;
}